package jdbc04;

import java.sql.*;

public class JDBCUtils {
//    构造函数私有化 不用在类外创建对象
    private JDBCUtils(){

    }
    /*数据库驱动常量*/
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    /*数据库连接 URL 常量*/
    private static final String URL =
            "jdbc:mysql://127.0.0.1/test?useSSL=false&characterEncoding=UTF-8";
    /*数据库登录用户名常量*/
    private static final String USER = "root";
    /*数据库登陆密码常量*/
    private static final String PASSWORD = "123456";
    /*注册驱动,当 jdbc06.JDBCUtils 类加载的时候,会执行静态代码块,此时会注册驱动*/
    static{
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() {
        Connection conn= null;
        try {
            conn= DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static void release(Connection con, Statement statement, ResultSet rs)
    {
        if (con!=null) {//避免空指针异常
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement!=null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
